package socketdemo;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {

    /*
     * 通过Socket封装的tcp协议来实现网络信息传输
     * */
    private Socket socket;

    public Client() {
        /*
         * host服务端的ip地址
         * port服务端所在服务器上所使用的端口号
         * */
        try {
            System.out.println("正在创建链接~");
            socket = new Socket("localhost", 8088);
            System.out.println("链接成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            //此处就是将 文件输出流 替换为了 Socket给我们返回的网络字节输出流
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw, true);//打开自动行刷新
            System.out.println("正在向服务端发送数据！");

            Runnable r = new ServerHandler();
            Thread t = new Thread(r);
            t.start();

            Scanner scanner = new Scanner(System.in);
            while (true) {
                System.out.println("请输入想要发送的消息:");
                String line = scanner.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

    private class ServerHandler implements Runnable {

        @Override
        public void run() {
            try {
                //网络输入流，读取数据
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
